<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

use yii\helpers\Json;

/* ====== 选项卡构建器 ====== */
/** @var \yii\web\View $this View实例 */
/** @var \builder\tab\TabBuilder $context 上下文实例 */
/** @var array $tabItem tab项 */
/** @var array $extraJs 额外的JS脚本 */

$context = $this->context;
$initTabProperty = '';
$tabSwitchMap = [];
?>
<script>
    !function (global, top) { "use strict";
        global.ym2App.controller("ym2.ctrl.<?= $context->id ?>", ["$scope", "ym2", "layui", function ($scope, ym2, layui) {
            var element = layui.element;
            var tabFilter = "ym2_builder_<?= $context->id ?>";
            var hashName = "tabid";
            var initTabProperty;
            // tab切换事件
            element.on("tab(" + tabFilter + ")", function (data) {
                var currentTabId = this.getAttribute('lay-id');
                var callback;
                location.hash = hashName + "=" + currentTabId;
                switch (currentTabId) {
                <?php foreach ($tabItem as $value): ?>

                    case "<?= $value['id'] ?>":
                    <?php if (!empty($value['reloadProperty'])): ?>
                    <?php $tabSwitchMap[$value['id']] = $value['reloadProperty']; ?>
                    <?php if ($value['selected']) $initTabProperty = $value['reloadProperty']; ?>

                        callback = global.ym2BehaviorReqExport["<?= $value['reloadProperty'] ?>"];
                        if (ym2.typeOf(callback) === "function") {
                            callback.call();
                        }
                    <?php endif; ?>

                        break;
                <?php endforeach; ?>

                }

            });
            // 初始化tab列表
            var tabSwitchMap = <?= Json::encode($tabSwitchMap) ?>;
            var layid = location.hash.replace(new RegExp("^#" + hashName + "="), "");
            if (layid) {
                element.tabChange(tabFilter, layid);
                initTabProperty = tabSwitchMap[layid] || "";
            } else {
                initTabProperty = "<?= $initTabProperty ?>";
            }
            angular.element(function () {
                if (
                    initTabProperty
                    && ym2.typeOf(global.ym2BehaviorReqExport[initTabProperty]) === "function"
                ) {
                    global.ym2BehaviorReqExport[initTabProperty].call();
                }
            });

            //额外的JS脚本
            <?= !empty($extraJs) ? implode("\n", $extraJs) : '' ?>

        }]);
    }(window, top);
</script>
